<template>


  <el-form :model="form" label-width="auto">
    <el-form-item label="角色名称">
      <el-input v-model="form.roleName"/>
    </el-form-item>

    <el-form-item label="设置菜单选项">
      <el-checkbox v-model="treeProp.strictly">父子不联动</el-checkbox>
    </el-form-item>


    <!--    <el-form-item label="  ">-->
    <!--      <el-checkbox v-model="treeProp.expand">展开折叠</el-checkbox>-->
    <!--      <el-checkbox v-model="treeProp.selectAll">全选/全不选</el-checkbox>-->
    <!--      <el-checkbox v-model="treeProp.strictly">父子联动</el-checkbox>-->
    <!--    </el-form-item>-->
    <el-form-item label="菜单权限">
      <el-tree
          style="max-width: 600px"
          :data="treeData"
          ref="treeRef"
          show-checkbox
          node-key="menuId"
          :check-strictly="treeProp.strictly"
          :props="menuTreeProps"
      />
    </el-form-item>


    <el-form-item>
      <el-button type="primary" @click="onSubmit">保存</el-button>
      <el-button @click="cancle">取消</el-button>
    </el-form-item>
  </el-form>

</template>

<script setup name='edit'>
import {nextTick, onMounted, reactive, ref} from "vue";
import {ElNotification} from 'element-plus'

//用于保存的API
import {initEdit, saveOrUpdate} from '@/api/permission/role/index'


//列表页传递的属性
//closeDialog 用于关闭dialog
// editId 编辑的id
const {closeDialog, editId} = defineProps(['closeDialog', 'editId'])

//表单数据
const form = ref({
  roleName: '',
  grantMenuIds: []
})


//菜单树的引用
const treeRef = ref()

/**
 * 定义菜单树形关联参数
 */
const treeProp = reactive({
  expand: true,
  selectAll: false,
  strictly: true     //父子不关联
})


//定义菜单树的  属性
const menuTreeProps = {
  label: 'menuName'
}

const treeData = ref([])


//保存按钮 点击事件
const onSubmit = () => {

  //将已授权的菜单id放到form中
  const chekedKeys = treeRef.value.getCheckedKeys()
  console.log("chekedKeys", chekedKeys)
  form.value.grantMenuIds = chekedKeys;

  //保存
  saveOrUpdate(form.value).then(success => {
    ElNotification({
      title: '消息',
      type: 'success',
      message: "保存成功",
    })

    //调用父组件中的 函数用于关闭 dialog 和更新查询结果
    closeDialog(true)
  })
}

const cancle = () => {
  //调用父组件中的 函数用于关闭 dialog 和更新查询结果
  closeDialog(false)
}


// 当修改操作的到时候 根据主键查询
async function pageGetById() {

  let info;
  if (editId) {
    info = await initEdit({id: editId});
  } else {
    info = await initEdit();
  }


  const {role, allMenuList, grantMenuIds} = info;

  //显示树形菜单
  treeData.value = allMenuList


  //显示角色基本信息
  if (role) {
    form.value = role
  }

  //勾选已授权的菜单
  if (grantMenuIds) {
    //设置已授权的菜单  勾选
    nextTick(() => {
      treeRef.value.setCheckedKeys(grantMenuIds)
    })
  }


}


onMounted(() => {
  //初始化页面
  pageGetById()


})


</script>

<style scoped></style>